<?php
App::uses('AppModel', 'Model');
/**
 * Post Model
 *
 * @property Category $Category
 */
class Post extends AppModel {

    public $name = "Post";

    #post status
    const typeStatus = 0;
    const draf = 0; #Save as draf
    const publish = 1; #Save as publish

    #Image Config
    const typeImage = 1;
    const smallCode = 'small';
    const mediumCode = 'medium';
    const bigCode = 'big';

    #post type
    const news = 1;

    var $actsAs = array(
        'MeioUpload.MeioUpload' => array(
            'image' => array(
                'removeOriginal' => true,
                'thumbnails' => true,
                'allowed_mime' => array('image/jpeg', 'image/pjpeg', 'image/gif', 'image/png'),
                'allowed_ext' => array('.jpg', '.jpeg', '.png', '.gif'),
                'thumbsizes' => array(
                    'small' => array('width' => 50),
                    'medium' => array('width' => 120),
                    'big' => array('width' => 255, 'watermark' => "watermark.png"),
                ),
                'default' => 'No-Image-Available.gif'
            ),
        ),
    );

    /**
     * Display field
     *
     * @var string
     */
    public $displayField = 'title';

    /**
     * Validation rules
     *
     * @var array
     */
    public $validate = array(
        'title' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Required',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'description' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Required',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'content' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Required',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'status' => array(
            'numeric' => array(
                'rule' => array('numeric'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'type' => array(
            'numeric' => array(
                'rule' => array('numeric'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'category_id' => array(
            'numeric' => array(
                'rule' => array('numeric'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'slug' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Required',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
            'unique' => array(
                'rule' => 'isUnique',
                'message' => 'This field existed',
            )
        ),
        'meta_keywords' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Required',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'meta_description' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Required',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'image' => array('Empty' => array('check' => false)),
    );

    //The Associations below have been created with all possible keys, those that are not needed can be removed

    /**
     * belongsTo associations
     *
     * @var array
     */
    public $belongsTo = array(
        'Category' => array(
            'className' => 'Category',
            'foreignKey' => 'category_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'Author' => array(
            'className' => 'User',
            'foreignKey' => 'created_by',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

    var $hasMany = array(
        'Comment' => array(
            'foreignKey' => 'owner_id',
            'conditions' => array('Comment.owner_model' => 'Post')
        )
    );

    //create slug
    public function beforeSave($options = array()) {
        if (empty($this->data["Post"]["slug"]) && !empty($this->data["Post"]["name"])) {
            $slug = $this->replaceAlpha($this->data["Post"]["name"]);
            $this->data["Post"]["slug"] = Inflector::slug($slug);
        }
        return true;
    }

    /**
     *
     * update Image Sizes when create post
     */
    public function updateImageSizes($object, $sizes) {
        $this->Behaviors->unload('MeioUpload.MeioUpload');

        //get thumbs image for variant from paramenters table
        $thumbs = array();
        foreach ($sizes as $i => $size) {
            $value = explode("x", $size['Parameter']['value']);
            $tmp = array('thumbnailQuality' => 100);

            if (!empty($value[0]) && !empty($value[1])) {
                $tmp['zoomCrop'] = true;
                $tmp['forceAspectRatio'] = 'C';
                $tmp['width'] = intval($value[0]);
                $tmp['height'] = intval($value[1]);
            } elseif (!empty($value[0])) {
                $tmp['width'] = intval($value[0]);
                $tmp['maxDimension'] = 'w';
            } elseif (!empty($value[1])) {
                $tmp['height'] = intval($value[1]);
                $tmp['maxDimension'] = 'h';
            }

            //add watermark
            if (!empty($value[0])) {
                switch (intval($value[0])) {
                    case intval($value[0]) >= 700:
                        $tmp['watermark'] = 'watermark_200.png';
                        break;
                    case intval($value[0]) >= 500:
                        $tmp['watermark'] = 'watermark_150.png';
                        break;
                    case intval($value[0]) >= 300:
                        $tmp['watermark'] = 'watermark_120.png';
                        break;
                    case intval($value[0]) >= 150:
                        $tmp['watermark'] = 'watermark_100.png';
                        break;
                }
            }
            $thumbs[$size['Parameter']['code']] = $tmp;
        }

        $meioUpload = array('removeOriginal' => true,
            'thumbnails' => true,
            'allowed_mime' => array('image/jpeg', 'image/pjpeg', 'image/gif', 'image/png'),
            'allowed_ext' => array('.jpg', '.jpeg', '.png', '.gif'),
            'default' => 'default.jpg',
            'thumbsizes' => $thumbs
        );

        if ($object == "Post") {
            $this->Behaviors->load('MeioUpload.MeioUpload', array('image' => $meioUpload));
        }
    }

    /**
     * get posts in the side
     */
    public function getPostSide() {
        $Post = new Post();
        $posts = $Post->find('all', array('limit' => 5, 'order' => 'Post.created_at desc',
            'conditions' => array('Post.status' => Post::publish)));
        return $posts;
    }

}
